<script lang="ts" setup>
import type { SchoolApi } from '#/api/edu/base/school';

import { ref } from 'vue';

import { confirm, Page, useVbenDrawer, useVbenModal } from '@vben/common-ui';
import { DICT_TYPE } from '@vben/constants';
import { downloadFileFromBlobPart, isEmpty } from '@vben/utils';

import { message } from 'ant-design-vue';

import { ACTION_ICON, TableAction, useVbenVxeGrid } from '#/adapter/vxe-table';
import {
  deleteSchool,
  exportSchool,
  getSchoolPage,
} from '#/api/edu/base/school';
import { DictTag } from '#/components/dict-tag';
import { $t } from '#/locales';

import { useGridColumns, useGridFormSchema } from './data';
import FastForm from './edit/fast-form.vue';
import Form from './edit/form.vue';
import Detail from './modules/detail.vue';

/** 快速创建/编辑学校信息 */
const [FastFormModal, fastFormModalApi] = useVbenModal({
  connectedComponent: FastForm,
  destroyOnClose: true,
});

const [FormDrawer, formDrawerApi] = useVbenDrawer({
  connectedComponent: Form,
  destroyOnClose: true,
});

const [DetailDrawer, detailDrawerApi] = useVbenDrawer({
  connectedComponent: Detail,
  destroyOnClose: true,
});
const desensitize = ref<boolean>(true); // 是否脱敏
function handleDesensitize() {
  desensitize.value = !desensitize.value;
  gridApi.reload();
}
/** 刷新表格 */
function handleRefresh() {
  gridApi.reload();
}

/** 创建学校信息 */
function handleCreate() {
  formDrawerApi.setData(null).open();
}

/** 快速创建/编辑学校信息 */
function handleFastCreate() {
  fastFormModalApi.setData(null).open();
}

/** 查看学校信息 */
function handleDetail(row: SchoolApi.School) {
  detailDrawerApi.setData(row).open();
}

/** 编辑学校信息 */
function handleEdit(row: SchoolApi.School) {
  formDrawerApi.setData(row).open();
}

/** 删除学校信息 */
async function handleDelete(row: SchoolApi.School) {
  const hideLoading = message.loading({
    content: $t('ui.actionMessage.deleting', [row.schoolId]),
    duration: 0,
  });
  try {
    await deleteSchool(row.schoolId!);
    message.success($t('ui.actionMessage.deleteSuccess', [row.schoolId]));
    handleRefresh();
  } finally {
    hideLoading();
  }
}

/** 批量删除学校信息 */
async function handleDeleteBatch() {
  await confirm($t('ui.actionMessage.deleteBatchConfirm'));
  const hideLoading = message.loading({
    content: $t('ui.actionMessage.deletingBatch'),
    duration: 0,
  });
  try {
    await deleteSchoolList(checkedIds.value);
    checkedIds.value = [];
    message.success($t('ui.actionMessage.deleteSuccess'));
    handleRefresh();
  } finally {
    hideLoading();
  }
}

const checkedIds = ref<number[]>([]);

function handleRowCheckboxChange({ records }: { records: SchoolApi.School[] }) {
  checkedIds.value = records.map((item) => item.schoolId!);
}

/** 导出表格 */
async function handleExport() {
  const data = await exportSchool(await gridApi.formApi.getValues());
  downloadFileFromBlobPart({ fileName: '学校信息.xls', source: data });
}

const [Grid, gridApi] = useVbenVxeGrid({
  formOptions: {
    schema: useGridFormSchema(),
    collapsed: true,
  },
  gridOptions: {
    id: 'School-grid',
    columns: useGridColumns(),
    height: 'auto',
    keepSource: true,
    proxyConfig: {
      ajax: {
        query: async ({ page }, formValues) => {
          return await getSchoolPage(
            {
              pageNo: page.currentPage,
              pageSize: page.pageSize,
              ...formValues,
            },
            desensitize.value,
            false,
          );
        },
      },
    },
    rowConfig: {
      keyField: 'SchoolId',
      isHover: true,
    },
    toolbarConfig: {
      refresh: true,
      search: true,
    },
  } as VxeTableGridOptions<SchoolApi.School>,
  gridEvents: {
    checkboxAll: handleRowCheckboxChange,
    checkboxChange: handleRowCheckboxChange,
  },
});
</script>

<template>
  <Page auto-content-height>
    <FormDrawer @success="handleRefresh" />
    <DetailDrawer @success="handleRefresh" />
    <FastFormModal @success="handleRefresh" />
    <Grid table-title="学校信息列表">
      <template #toolbar-tools>
        <TableAction
          :actions="[
            {
              label: desensitize ? '关闭脱敏' : '启用脱敏',
              type: 'primary',
              danger: desensitize,
              icon: desensitize
                ? 'ant-design:eye-filled'
                : 'ant-design:eye-invisible-filled',
              auth: ['edu:base:admin-department:query'],
              onClick: handleDesensitize,
            },
            {
              label: '快速创建',
              type: 'primary',
              icon: ACTION_ICON.ADD,
              auth: ['edu:base:school:create'],
              onClick: handleFastCreate,
            },
            {
              label: $t('ui.actionTitle.create', ['学校信息']),
              type: 'primary',
              icon: ACTION_ICON.ADD,
              auth: ['edu:base:school:create'],
              onClick: handleCreate,
            },
            {
              label: $t('ui.actionTitle.export'),
              type: 'primary',
              icon: ACTION_ICON.DOWNLOAD,
              auth: ['edu:base:school:export'],
              onClick: handleExport,
            },
            {
              label: $t('ui.actionTitle.deleteBatch'),
              type: 'primary',
              danger: true,
              icon: ACTION_ICON.DELETE,
              disabled: isEmpty(checkedIds),
              auth: ['edu:base:school:delete'],
              onClick: handleDeleteBatch,
            },
          ]"
        />
      </template>
      <template #periodList="{ row }">
        <DictTag :value="row.periodList" :type="DICT_TYPE.EDU_PERIOD" />
      </template>
      <template #actions="{ row }">
        <TableAction
          :actions="[
            {
              label: '查看',
              type: 'link',
              icon: ACTION_ICON.VIEW,
              auth: ['edu:base:school:query'],
              onClick: handleDetail.bind(null, row),
            },
            {
              label: $t('common.edit'),
              type: 'link',
              icon: ACTION_ICON.EDIT,
              auth: ['edu:base:school:update'],
              onClick: handleEdit.bind(null, row),
            },
            {
              label: $t('common.delete'),
              type: 'link',
              danger: true,
              icon: ACTION_ICON.DELETE,
              auth: ['edu:base:school:delete'],
              popConfirm: {
                title: $t('ui.actionMessage.deleteConfirm', [row.SchoolId]),
                confirm: handleDelete.bind(null, row),
              },
            },
          ]"
        />
      </template>
    </Grid>
  </Page>
</template>
